/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/insertion-sort-list
   @Language: C++
   @Datetime: 16-02-09 04:49
   */

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
	/**
	 * @param head: The first node of linked list.
	 * @return: The head of linked list.
	 * Tip: traversal each list node, insert it into ordered list
	 */
	ListNode *insertionSortList(ListNode *head) {
		// write your code here
		ListNode H(-1), *p, *q;
		while(head){
			for(p=&H; (q=p->next) && q->val<=head->val; p=p->next);
			p = p->next = head;	// p<=head, q>head
			head = head->next;
			p->next = q;		// relink to ordered list part
		}
		return H.next;
	}
};
